import { createRouter, createWebHashHistory } from "vue-router";
import { ElMessage } from "element-plus";

import HomePage from "@/views/Home/HomePage.vue";
import LoginPage from "@/views/Login/LoginPage.vue";
import HomeIndex from "@/components/HomeIndex/HomeIndex.vue";
import BannerList from "@/components/Banner/BannerList.vue";
import CreateBanner from "@/components/Banner/CreateBanner.vue";
import ProductList from "@/components/ProductAdmin/ProduceList.vue";

const routes = [
  { path: "/", redirect: "/login" },
  { path: "/login", component: LoginPage },
  {
    path: "/home",
    component: HomePage,
    children: [
      {
        path: "/home/index",
        component: HomeIndex,
        title: "系统首页",
      },
      {
        path: "/banner/list",
        component: BannerList,
        title: "轮播图管理",
        parent: { title: "轮播图列表", to: "/banner/list" },
      },
      {
        path: "/banner/create",
        component: CreateBanner,
        title: "轮播图管理",
        parent: { title: "创建轮播图", to: "/banner/create" },
      },
      {
        path: "/product/admin",
        component: ProductList,
        title: "商品管理",
      },
      {
        path: "/product/admin",
        component: ProductList,
        title: "数据可视化",
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to) => {
  const userLS = JSON.parse(localStorage.getItem("userInfo"));
  if (to.path !== "/login" && !userLS?.token) {
    ElMessage.error("v我50再进来");
    return { path: "/" };
  }
});

// const tmp = [
//   { title: '首页', to: '路径', children?:[ {title: '首页', to: '路径'}, { title: '首页', to: '路径' } ] }
// ]
const filterRoutes = (routes) => {
  const items = routes[2]?.children || [];
  // 定义输出数据
  const menus = [];
  items.forEach((item) => {
    if (menus.length === 0) {
      // menus里没有数据
      menus.push({
        title: item.title,
        to: item.path,
        children: [],
      });
      if (item.parent)
        menus[0].children.push({
          title: item.parent.title,
          to: item.parent.to,
        });
    } else {
      // 如果menus里已经有数据了
      const tmp = menus.find((v) => {
        return v.title === item.title;
      });
      if (tmp) {
        tmp.children.push({
          title: item.parent.title,
          to: item.parent.to,
        });
      } else {
        menus.push({
          title: item.title,
          to: item.path,
          children: [],
        });
        if (item.parent)
          menus[menus.length - 1].children.push({
            title: item.parent.title,
            to: item.parent.to,
          });
      }
    }
  });
  return menus;
};

export const menus = filterRoutes(routes);

export default router;
